﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace BiliData
{
    public partial class Form1 : Form
    {
        [DllImport("Kernel32.dll")]
        static extern Boolean AllocConsole();

        int xWindowsWidth1;     //屏幕分辨率 宽
        int yWindowsHeight1;    //屏幕分辨率 窄
        int oldX, oldY;         //按下窗口的位置

        //获取数据定时器
        private System.Windows.Forms.Timer timerGet = new System.Windows.Forms.Timer();

        
        public Form1()
        {
            InitializeComponent();
            //AllocConsole();

            xWindowsWidth1 = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width;//获取显示器屏幕宽度
            yWindowsHeight1 = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height;//高度

            textBoxUrl.Text = "";
            textBoxCookie.Text = "";

            IniFileHelper iniFileHelper = new IniFileHelper("./EZConfig.ini");
            StringBuilder sb = new StringBuilder(2048);

            //读取首页地址和Cookie
            iniFileHelper.GetIniString("EZTech", "HomePage", "", sb, sb.Capacity);
            textBoxUrl.Text = sb.ToString();
            iniFileHelper.GetIniString("EZTech", "Cookie", "", sb, sb.Capacity);
            textBoxCookie.Text = sb.ToString();

            if(textBoxUrl.Text != "" && textBoxCookie.Text != "")   //如果内容都不为空
            {
                GetBilibiliData();  //获取一次数据
            }
            
            timerGet.Tick += new EventHandler(timerGet_Tick);//事件处理
            timerGet.Enabled = true;//设置启用定时器
            timerGet.Interval = 1000 * 60 * 60;//执行时间，此处一小时
            timerGet.Start();//开启定时器
        }

        private void timerGet_Tick(object sender, EventArgs e)
        {
            GetBilibiliData();    //获取数据
        }

        public int HttpGet(string url, out string reslut)
        {
            reslut = "";
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                //CookieContainer ckCtnr = new CookieContainer();

                if(textBoxCookie.Text == "")
                    return -1;

                wbRequest.Method = "GET";
                wbRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36";
                wbRequest.Headers.Add("Cookie", textBoxCookie.Text); //添加Cookie

                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    System.Console.WriteLine(wbResponse.GetResponseHeader("Authorization"));

                    using (StreamReader sReader = new StreamReader(responseStream))
                    {
                        reslut = sReader.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                reslut = e.Message;     //输出捕获到的异常，用OUT关键字输出
                MessageBox.Show(reslut, "温馨提示：", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return -1;              //出现异常，函数的返回值为-1
            }
            return 0;
        }

        //保存首页地址和Cookie
        private void WriteIni()
        {
            IniFileHelper iniFileHelper = new IniFileHelper("./EZConfig.ini");

            iniFileHelper.WriteIniString("EZTech", "HomePage", textBoxUrl.Text);
            iniFileHelper.WriteIniString("EZTech", "Cookie", textBoxCookie.Text);
        }

        //检测首页地址是否正确
        private string DetectMid(string url_str)
        {
            Regex reg = new Regex("^[0-9]*$");//判断整个字符串是否都为数字

            string[] url_split = url_str.Split('/');

            for(int i = 0;i < url_split.Length;i++)
            {
                string[] url_split_question = url_split[i].Split('?');
                if (url_split_question[0].Length >= 8 && reg.IsMatch(url_split_question[0]))    //全是数字，且长度大于8
                {
                    return url_split_question[0];
                }
            }

            return "";
        }

        //获取数据
        private void GetBilibiliData()
        {
            string url_get_str;
            string url_vmid_set = "";   //粉丝数
            string url_mid_set = "";    //获赞和播放量
            string user_mid = "";
            // https://api.bilibili.com/x/relation/stat // vmid=粉丝数
            // https://api.bilibili.com/x/space/upstat // mid=获赞和视频播放量

            user_mid = DetectMid(textBoxUrl.Text);  //获取MID
            if (user_mid != "") //判断MID
            {
                url_vmid_set = "https://api.bilibili.com/x/relation/stat?vmid=" + user_mid;
                url_mid_set = "https://api.bilibili.com/x/space/upstat?mid=" + user_mid;

                if (HttpGet(url_vmid_set, out url_get_str) == 0)
                {
                    try
                    {
                        JObject jb1 = (JObject)JsonConvert.DeserializeObject(url_get_str);
                        System.Console.WriteLine(jb1["data"]["follower"].ToString());
                        labelFans.Text = jb1["data"]["follower"].ToString();
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Cookie错误", "温馨提示：", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                if (HttpGet(url_mid_set, out url_get_str) == 0)
                {
                    try
                    {
                        JObject jb2 = (JObject)JsonConvert.DeserializeObject(url_get_str);
                        System.Console.WriteLine(jb2["data"]["archive"]["view"].ToString());
                        System.Console.WriteLine(jb2["data"]["likes"].ToString());
                        labelPlay.Text = jb2["data"]["archive"]["view"].ToString();
                        labelLike.Text = jb2["data"]["likes"].ToString();
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Cookie错误", "温馨提示：", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
            }
                WriteIni();
            }
            else
            {
                MessageBox.Show("输入的B站首页有问题！", "温馨提示：", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        //鼠标按下时窗口的位置
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            //判断是否为鼠标左键
            if (e.Button == MouseButtons.Left)
            {
                //获取鼠标左键按下时的位置
                this.oldX = e.Location.X;
                this.oldY = e.Location.Y;
            }
        }

        //页面移动
        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                //计算鼠标移动距离
                System.Console.WriteLine("Left=" + this.Left + "Location.X=" + e.Location.X + "this.Left+++=" + (this.Left + e.Location.X + this.Width) + "xWindowsWidth1=" + xWindowsWidth1);

                if(this.Left + e.Location.X - this.oldX + this.Width > xWindowsWidth1)
                {
                    this.Left = xWindowsWidth1 - this.Width;
                }
                else if(this.Left + e.Location.X - this.oldX < 0)
                {
                    this.Left = 0;
                }
                else
                {
                    this.Left += e.Location.X - this.oldX;
                }

                if (this.Top + e.Location.Y - this.oldY + this.Height > yWindowsHeight1)
                {
                    this.Top = yWindowsHeight1 - this.Height;
                }
                else if (this.Top + e.Location.Y - this.oldY < 0)
                {
                    this.Top = 0;
                }
                else
                {
                    this.Top += e.Location.Y - this.oldY;
                }
            }
        }

        //退出按钮按下
        private void buttonExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //获取按钮按下
        private void buttonMonitor_Click(object sender, EventArgs e)
        {
            GetBilibiliData();
        }
    }
}
